package com.campsys.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campsys.core.Result;
import com.campsys.core.TableData;
import com.campsys.domain.TManagerStudent;
import com.campsys.domain.TManagerTeacher;
import com.campsys.domain.param.*;
import com.campsys.domain.vo.*;
import com.campsys.mapping.StudentMapping;
import com.campsys.mapping.TeacherMapping;
import com.campsys.service.IClazzService;
import com.campsys.service.IStudentService;
import com.campsys.util.StudentBatchAddListener;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "学员管理")
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IClazzService clazzService;

    @ApiOperation("添加学生")
    @PreAuthorize("@lcc.myAuthority('student:add')")
    @PostMapping("/add")
    public Result addStudent(@Validated @RequestBody StudentAddParam studentAddParam){

        boolean rs = studentService.addStudent(studentAddParam);
        return rs ? Result.success() : Result.error();
    }

    @ApiOperation("修改学生信息")
    @PreAuthorize("@lcc.myAuthority('student:update')")
    @PutMapping("/update")
    public Result updateStudent(@Validated @RequestBody StudentUpdateParam studentUpdateParam){

        TManagerStudent tManagerStudent = StudentMapping.INSTANCE.to(studentUpdateParam);

        boolean rs = studentService.updateById(tManagerStudent);

        return rs ? Result.success() : Result.error();
    }

    @ApiOperation("删除学生")
    @PreAuthorize("@lcc.myAuthority('student:delete')")
    @PutMapping("/delete/{id}")
    public Result deleteStudent(@PathVariable Long id){

        boolean rs = studentService.deleteStudent(id);

        return rs ? Result.success() : Result.error();
    }

    @ApiOperation("查询学生分页列表")
    @PreAuthorize("@lcc.myAuthority('student:page')")
    @GetMapping("/page")
    public TableData getStudentPage(@Validated PageParam pageParam, String name, Long clazzId){

        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtil.isNullOrEmpty(name),TManagerStudent::getStuName,name);
        qw.eq(TManagerStudent::getDeleteStatus,0);

        List<Long> studentIds = clazzService.getStudentIdsInClazz(clazzId);
        if (clazzId != null && (studentIds == null || studentIds.isEmpty())) {
            // 如果 studentIds 为空，则返回空的分页结果
            return TableData.success(new ArrayList<>(), 0L);
        }
        qw.in(clazzId != null && studentIds.size() != 0,TManagerStudent::getId,studentIds);

        Page<TManagerStudent> studentPage = new Page<>(pageParam.getPageNum(),pageParam.getPageSize());

        Page<TManagerStudent> page = studentService.page(studentPage,qw);

        List<StudentPageVo> list = StudentMapping.INSTANCE.toPage(page.getRecords());

        return TableData.success(list,page.getTotal());

    }

    @ApiOperation("查询学生列表（已审核）")
    @PreAuthorize("@lcc.myAuthority('student:list:review')")
    @GetMapping("/list/review")
    public Result getStudentListReview(){

        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
        qw.eq(TManagerStudent::getStatus,1);
        qw.ne(TManagerStudent::getDeleteStatus,1);

        List<StudentListVo> list = StudentMapping.INSTANCE.toList(studentService.list(qw));

        return Result.success(list);
    }

    @ApiOperation("查询学生列表（未审核）")
    @PreAuthorize("@lcc.myAuthority('student:list:notReview')")
    @GetMapping("/list/notReview")
    public Result getStudentListNotReview(){

        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
        qw.eq(TManagerStudent::getStatus,0);
        qw.ne(TManagerStudent::getDeleteStatus,1);

        List<StudentListVo> list = StudentMapping.INSTANCE.toList(studentService.list(qw));

        return Result.success(list);
    }

    @ApiOperation("审核学生通过")
    @PreAuthorize("@lcc.myAuthority('student:review')")
    @PutMapping("/review")
    public Result reviewStudent(@RequestBody List<Long> ids){

        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
        qw.in(TManagerStudent::getId,ids);

        TManagerStudent tManagerStudent = new TManagerStudent();
        tManagerStudent.setStatus("1");

        boolean rs = studentService.update(tManagerStudent,qw);

        return rs ? Result.success() : Result.error();
    }

    @ApiOperation("查询学生详情")
    @PreAuthorize("@lcc.myAuthority('student:detail')")
    @GetMapping("/detail/{id}")
    public Result getStudentDetail(@PathVariable Long id){

        StudentInfoVo studentInfoVo = StudentMapping.INSTANCE.to(studentService.getById(id));
        return Result.success(studentInfoVo);
    }

    @ApiOperation("批量导入学生")
    @PreAuthorize("@lcc.myAuthority('student:addBatch')")
    @PostMapping("/addBatch")
    @ResponseBody
    public Result addBatch(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), StudentAddExcel.class, new StudentBatchAddListener(studentService)).sheet().doRead();
            return Result.success("文件上传成功");
        } catch (IOException e) {
            return Result.error("文件上传失败");
        }
    }

    @ApiOperation("下载批量导入学生模板")
    @PreAuthorize("@lcc.myAuthority('student:export:template')")
    @PostMapping("/export/template")
    public void uploadTemplate(HttpServletResponse response) {

        List<StudentAddExcel> list = new ArrayList<>();
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("content-Disposition","attachment;filename="+ URLEncoder.encode("测试模板","UTF-8")+".xlsx");
            EasyExcel.write(response.getOutputStream(),StudentAddExcel.class).sheet().doWrite(list);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ApiOperation("根据loginId获取studentId")
    @PreAuthorize("@lcc.myAuthority('student:get:id')")
    @GetMapping("/get/id/{userId}")
    public Result getStudentId(@PathVariable Long userId){

        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
        qw.eq(TManagerStudent::getLoginId,userId);

        TManagerStudent tManagerStudent = studentService.getOne(qw);

        return Result.success(tManagerStudent.getId());
    }

//    @ApiOperation("根据studentId获取教学班")
//    @PreAuthorize("@lcc.myAuthority('student:get:id')")
//    @GetMapping("/get/id/{userId}")
//    public Result getStudentId(@PathVariable Long userId){
//
//        LambdaQueryWrapper<TManagerStudent> qw = new LambdaQueryWrapper<>();
//        qw.eq(TManagerStudent::getLoginId,userId);
//
//        TManagerStudent tManagerStudent = studentService.getOne(qw);
//
//        return Result.success(tManagerStudent.getId());
//    }


}
